package com.handoop.gms.service.imp;

import com.handoop.gms.config.Configuration;
import com.handoop.gms.dao.DaoSupport;
import com.handoop.gms.domain.Competition;
import com.handoop.gms.domain.Page;
import com.handoop.gms.domain.Place;
import com.handoop.gms.domain.RentPlace;
import com.handoop.gms.service.ComService;
import com.handoop.gms.service.PlaceService;
import com.handoop.gms.service.RentPlaceService;
import com.handoop.gms.utils.QueryHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2015-1-6.
 */
@Service
@Transactional
public class ComServiceImp implements ComService {


    @Autowired private DaoSupport<Competition> daoSupport;
    @Autowired private PlaceService placeService;
    @Autowired private RentPlaceService rentService;

    @Override
    public boolean createCompetition(Competition comp) {
        int result = daoSupport.append(new QueryHelper()
                .setNameSpace(Competition.class.getSimpleName())
                .setSql_method("insert_one")
                .setValue(comp));
        return result>0?true:false;
    }

    @Override
    public boolean createCompetition(Competition comp, Long[] placeId, Date[] begin, Date[] end) {
        this.createCompetition(comp);
        if (placeId!=null){
            List<RentPlace> rents = new ArrayList<RentPlace>();
            for (int i=0; i<placeId.length; i++){
                Place place = placeService.getPlaceById(placeId[i]);
                if (place!=null){
                    RentPlace rent = new RentPlace();
                    rent.setCreateDate(new Date());
                    rent.setPlace(place);
                    rent.setCompetition(comp);
                    rent.setLevel(1);
                    rent.setBegin(begin[i]);
                    rent.setEnd(end[i]);
                    rents.add(rent);
                }else throw new RuntimeException();
                rentService.batCreateRent(rents);
            }
            return true;
        }else throw new RuntimeException();
    }

    @Override
    public Page getCompPage(int pageNum) {
        List<Competition> comps = daoSupport.findAllByValue(new QueryHelper()
                .setNameSpace(Competition.class.getSimpleName())
                .setSql_method("select_full")
                .setParams("index", (pageNum-1)* Configuration.DEFAULT_PAGESIZE)
                .setParams("size", Configuration.DEFAULT_PAGESIZE));
        int result = daoSupport.recordCount(new QueryHelper()
                .setNameSpace(Competition.class.getSimpleName())
                .setSql_method("select_full_count"));
        return new Page(pageNum, Configuration.DEFAULT_PAGESIZE, result, comps);
    }
}
